package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"errors"
)

//RSA/ECB/PKCS1Padding

// RsaEncrypt RSA加密
func RsaEncrypt(publicKeyStr, originalData string) (string, error) {
	// 先Base64解码公钥
	decodedKey, err := base64.StdEncoding.DecodeString(publicKeyStr)
	if err != nil {
		return "", err
	}

	// 解析公钥
	pubInterface, err := x509.ParsePKIXPublicKey(decodedKey)
	if err != nil {
		return "", err
	}

	pub, ok := pubInterface.(*rsa.PublicKey)
	if !ok {
		return "", errors.New("not an RSA public key")
	}

	// 加密
	encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(originalData))
	if err != nil {
		return "", err
	}

	// Base64编码
	return base64.StdEncoding.EncodeToString(encryptedData), nil
}

// RsaDecrypt RSA解密
func RsaDecrypt(privateKeyStr, encryptedData string) (string, error) {
	// 解析私钥
	// 先Base64解码
	decodedKey, err := base64.StdEncoding.DecodeString(privateKeyStr)
	if err != nil {
		return "", err
	}

	// 使用ParsePKCS8PrivateKey解析PKCS#8格式私钥
	privInterface, err := x509.ParsePKCS8PrivateKey(decodedKey)
	if err != nil {
		return "", err
	}

	// 类型断言为*rsa.PrivateKey
	priv, ok := privInterface.(*rsa.PrivateKey)
	if !ok {
		return "", errors.New("not an RSA private key")
	}

	// Base64解码
	decodedData, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return "", err
	}

	// 解密
	decryptedData, err := rsa.DecryptPKCS1v15(rand.Reader, priv, decodedData)
	if err != nil {
		return "", err
	}

	return string(decryptedData), nil
}
